#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/uaccess.h>

static unsigned int dev_major = 500;
static struct class *devcls;
static struct device *dev;


int c0_open(struct inode *inode,struct file *filp)
{
	printk("---------%s--------\n",__FUNCTION__);
	return 0;
}
ssize_t c0_read(struct file *filp,char __user *buf,size_t count,loff_t *fpos)
{
	int ret;
	int knum = 520;
	ret = copy_to_user(buf,&knum,count);
	if(ret != 0)
	{
		printk("copy_to_user failed\n");
		return -EFAULT;
	}
	return 0;
}
ssize_t c0_write(struct file *filp,const char __user *buf,size_t count,loff_t *fpos)
{
	int ret;
	int value;
	ret = copy_from_user(&value,buf,count);
	if(ret != 0)
	{
		printk("copy_from_user failed\n");
		return -EFAULT;
	}
	printk("kernel value: %d\n",value);
	return 0;
}
int c0_close(struct inode *inode,struct file *filp)
{
	printk("---------%s--------\n",__FUNCTION__);
	return 0;
}

const struct file_operations my_fops={
	.open = c0_open,
	.read = c0_read,
	.write = c0_write,
	.release = c0_close,
};


static int __init chr_dev_init(void)
{
	int ret;
	ret=register_chrdev(dev_major,"chr_dev_test",&my_fops);
	if(ret==0)
	{
		printk("register ok\n");
	}
	else
	{
		printk("register failed\n");
		return -EINVAL;
	}
	devcls = class_create(THIS_MODULE,"chr_cls");
	dev = device_create(devcls,NULL,MKDEV(dev_major,0),NULL,"c0");

	return 0;
}

static void __exit chr_dev_exit(void)
{
	device_destroy(devcls,MKDEV(dev_major,0));
	class_destroy(devcls);
	unregister_chrdev(dev_major,"chr_dev_test");
	printk("exit ok\n");
}

module_init(chr_dev_init);
module_exit(chr_dev_exit);
MODULE_LICENSE("GPL");

